package com.centanet.framework.task;

import android.os.AsyncTask;

import com.centanet.framework.interfaces.IUploadParse;
import com.centanet.framework.interfaces.IUploadResult;
import com.centanet.framework.model.UploadModel;
import com.orhanobut.logger.Logger;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;

/**
 * 上传任务-解析类型String格式
 */
public class StringUploadTask extends AsyncTask<Void, Void, UploadModel<String>> implements IUploadParse<String> {

    private final static String TAG = "StringUploadTask";

    private final OkHttpClient okHttpClient;
    private final String url;
    private final String path;
    private final RequestBody requestBody;
    private final IUploadResult<String> iUploadResult;

    /**
     * @param okHttpClient  {@link OkHttpClient}
     * @param url           上传地址
     * @param path          文件路径
     * @param requestBody   请求body
     * @param iUploadResult 上传结果回调
     */
    public StringUploadTask(OkHttpClient okHttpClient, String url, String path, RequestBody requestBody, IUploadResult<String> iUploadResult) {
        this.okHttpClient = okHttpClient;
        this.url = url;
        this.path = path;
        this.requestBody = requestBody;
        this.iUploadResult = iUploadResult;
    }

    @Override
    protected UploadModel<String> doInBackground(Void... params) {
        Logger.t(TAG).d("Upload start path : %s", path);
        final Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            final Response response = okHttpClient.newCall(request).execute();
            Logger.t(TAG).d("upload result code: %d \t message : %s", response.code(), response.message());
            return new UploadModel<>(response.code() == 200, prarse(response), path);
        } catch (IOException e) {
            e.printStackTrace();
            Logger.t(TAG).e(e, "上传出错");
            return new UploadModel<>(false, "", path);
        }
    }


    @Override
    protected void onPostExecute(UploadModel<String> uploadModel) {
        super.onPostExecute(uploadModel);
        iUploadResult.result(uploadModel);
    }

    @Override
    public String prarse(Response response) throws IOException {
        return response.body().string();
    }
}
